package com.cxyzy.clipboardchannel

import android.app.Activity
import android.content.*

class ClipperReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val cb = context
            .getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        if (isActionSet(intent.action)) {
            val text = intent.getStringExtra(EXTRA_TEXT)
            if (text != null) {
                cb.setPrimaryClip(ClipData.newPlainText("", text))
                resultCode = Activity.RESULT_OK
                resultData = "Copied to phone."
            } else {
                resultCode = Activity.RESULT_CANCELED
                resultData = "No text is provided. Use -e text \"text to be pasted\""
            }
        } else if (isActionGet(intent.action)) {
            val clip: CharSequence = cb.primaryClip.toString()
            resultCode = Activity.RESULT_OK
            resultData = clip.toString()
        }
    }

    private fun isActionGet(action: String?): Boolean {
        return ACTION_GET == action || ACTION_GET_SHORT == action
    }

    private fun isActionSet(action: String?): Boolean {
        return ACTION_SET == action || ACTION_SET_SHORT == action
    }
}